import Strings from '@/i18n';
import {
  DialogInstance,
  Dialog,
  Cell,
  Switch as OriginalSwitch,
  SmartSwitchProps,
} from '@ray-js/smart-ui';
import {
  ScrollView,
  PageContainer,
  View,
  Text,
  Image,
  publishDps,
  event,
  showToast,
} from '@ray-js/ray';
import React, { useEffect, useRef, useState } from 'react';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import { useWaterControlInfo, GroupedSwitchInfo } from '@/hooks/useWaterControlInfo';
import { saveCloudData } from '@/api';
import { useDispatch, useSelector } from 'react-redux';
import { updateGroupNames } from '@/redux/modules/cloudStateSlice';
import res from '@/res/images';
import useHandleJump from '@/hooks/useHandleJump';
import { useProps } from '@ray-js/panel-sdk';
import CountdownActionSheet from '@ray-js/countdown-action-sheet';
import {
  decodeNormalTimer,
  formatTimeString,
  getNearlyTask,
  decodeCycleTimer,
  encodeAllNormalTimer,
  encodeAllCycleTimer,
} from '@/utils/timer';
import { ReduxState } from '@/redux';
import styles from './index.module.less';
import { decodeArea, encodeArea } from '@/pages/AreaSet';
import clsx from 'clsx';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;
export const SwitchWihtLoading = (props: any) => {
  const [loading, setLoading] = useState(false);

  const valueRef = useRef(props.checked);

  useEffect(() => {
    let timer;
    if (loading) {
      timer = setTimeout(() => {
        setLoading(false);
      }, 10 * 1000);
    }
    return () => {
      clearTimeout(timer);
    };
  }, [loading]);

  useEffect(() => {
    if (props.checked !== valueRef.current) {
      valueRef.current = props.checked;
      setLoading(false);
    }
  }, [props.checked]);

  return (
    <OriginalSwitch
      {...props}
      loading={loading}
      onChange={async value => {
        setLoading(true);
        props.onChange?.(value);
      }}
    />
  );
};

export const GroupInfo = () => {
  const waterControlInfo = useWaterControlInfo();

  const {
    general_timing: generalTiming,
    cycle_timing1: cycleTiming1,
    cycle_timing2: cycleTiming2,
    weather_delay: weatherDelay,
  } = useProps();

  const { delayTime } = useSelector((state: ReduxState) => state.cloudState);

  const normalDataSource = decodeNormalTimer(generalTiming, true, {});
  const cycleDataSource1 = decodeCycleTimer(cycleTiming1, true, {});
  const cycleDataSource2 = decodeCycleTimer(cycleTiming2, true, {});

  const cycleDataSource = [...cycleDataSource1, ...cycleDataSource2];
  console.log(`🚀 ~ cycleDataSource:`, cycleDataSource, normalDataSource);

  const props = useProps();

  const { irrigation_area: irrigationArea } = useProps();

  const area = irrigationArea?.length === 2 ? decodeArea(irrigationArea) : '11111';

  const dispatch = useDispatch();
  const [show, setShow] = useState(false);
  const [select, setSelect] = useState<GroupedSwitchInfo>();

  const [countDown, setCountDown] = useState('');
  const [showCountDown, setShowCountDown] = useState(false);

  const beforeClose = (
    action: 'cancel' | 'confirm' | 'overlay',
    value?: string
  ): Promise<boolean> =>
    new Promise(resolve => {
      setTimeout(() => {
        if (action === 'confirm') {
          dispatch(
            updateGroupNames({
              [`${select.groupId}`]: value || `组${select.groupId.split('_')[1]}`,
            })
          );
          saveCloudData({
            code: select.groupId,
            value,
          });

          setShow(false);
          resolve(true);
        } else {
          // 拦截取消操作
          resolve(true);
        }
      }, 10);
    });

  const showDetail = (item: any) => {
    setSelect(item);
    setShow(true);
  };

  const handleJump = useHandleJump();

  const handleDelete = () => {
    const deleteId = select.groupId;
    console.log(`🚀 ~ select:`, select);

    const newGroup = waterControlInfo.map(item => {
      if (item.groupId === deleteId) {
        return 0;
      }
      return item.hide ? 0 : 1;
    });

    const str = parseInt(newGroup.reverse().join(''), 2).toString(16).padStart(2, '0');

    const newNormalTimeDataSource = normalDataSource.filter(
      item => ![select.water.areaInTimer, select.drug.areaInTimer].includes(item.areaStr)
    );

    const newCycleTimeDataSource = cycleDataSource.filter(
      item => ![select.water.areaInTimer, select.drug.areaInTimer].includes(item.areaStr)
    );

    const areaArr = area.split('');

    areaArr[select.group - 1] = 0;

    publishDps({
      device_num: str,
      irrigation_area: encodeArea(areaArr.join('')),
    });

    setShow(false);
  };

  const getBatteryIcon = battery => {
    if (battery > 80) {
      return res.battery4;
    }

    if (battery > 60) {
      return res.battery3;
    }

    if (battery > 40) {
      return res.battery2;
    }

    if (battery > 10) {
      return res.battery1;
    }

    return res.battery0;
  };

  return (
    <>
      <ScrollView
        style={{
          height: `calc(${height}px - env(safe-area-inset-bottom) - env(safe-area-inset-top) )`,
          marginTop: '30rpx',
        }}
        scrollY
      >
        <View
          style={{
            paddingBottom: '400rpx',
            marginBottom: '400rpx',
          }}
        >
          {waterControlInfo
            .filter(item => !item.hide)
            .map(item => (
              <View
                className={clsx(styles.infoContainer, { [styles.offLineBox]: item.isOffLine })}
                key={item.groupId}
              >
                <View className={styles.infoTitle} onClick={() => showDetail(item)}>
                  <View className={styles.title}>
                    <Text>{item.name}</Text>
                  </View>
                  <View className={styles.infoTitleRight}>
                    <Text className={styles.batteryText}>{item.battery}%</Text>
                    <Image src={getBatteryIcon(item.battery)} className={styles.batteryIcon} />
                    <Image src={res.arrow} className={styles.arrow} />
                  </View>
                </View>
                <View className={styles.infoContentContainer}>
                  {[item.water, item.drug].map((ele, index) => {
                    const timeListWater = [
                      ...normalDataSource,
                      ...cycleDataSource1,
                      ...cycleDataSource2,
                    ].filter(i => i.areaStr === ele.areaInTimer && i.power);

                    const { nextTime, waterTime, nextTimeValue } = getNearlyTask(
                      timeListWater,
                      delayTime,
                      weatherDelay
                    );
                    return (
                      <View key={index}>
                        <View
                          className={styles.itemTopContainer}
                          onClick={() => {
                            handleJump(
                              `logPage?switchId=${ele.dpId}&nextTime=${nextTimeValue}&waterTime=${waterTime}`
                            );
                          }}
                        >
                          <View className={styles.itemTopContent}>
                            <Image src={ele.pic} className={styles.switchPic} />
                            <View className={styles.itemTopTextContainer}>
                              <View className={styles.deviceName}>{ele.name}</View>
                              <Text className={styles.statusText}>
                                {`${Strings.getLang('next_irrigation_time')} ${nextTime}`}
                              </Text>
                            </View>
                          </View>

                          <Image src={res.edit} className={styles.edit} />
                        </View>

                        <View className={styles.itemBottomContainer}>
                          <View className={styles.switchContainer}>
                            <SwitchWihtLoading
                              checked={props[ele.dpId]}
                              onChange={event => {
                                if (index === 1 && props[ele.dpId]) {
                                  showToast({
                                    title: Strings.getLang('drugOnTip'),
                                    icon: 'none',
                                  });
                                  return;
                                }
                                publishDps({
                                  [ele.dpId]: !props[ele.dpId],
                                });
                              }}
                            />
                            <Text className={styles.statusText}>
                              {props[ele.dpId]
                                ? Strings.getLang('waterOn')
                                : Strings.getLang('waterOff')}
                            </Text>
                          </View>
                          <View
                            className={styles.timeContainer}
                            onClick={() => {
                              if (index === 0) {
                                setCountDown(ele.timerDpName);
                                setShowCountDown(true);
                              }

                              if (index === 1) {
                                showToast({
                                  title: Strings.getLang('drugtimeTip'),
                                  icon: 'none',
                                });
                              }
                            }}
                          >
                            <View className={styles.timeText}>
                              {formatTimeString(props[ele.timerDpName])}
                            </View>
                            <View className={styles.statusText}>
                              {Strings.getLang(index === 0 ? 'waterTime' : 'drugTime')}
                            </View>
                          </View>
                        </View>
                      </View>
                    );
                  })}
                  {item.isOffLine && (
                    <View className={styles.offLine}>
                      <Image src={res.offline} className={styles.offLineIcon} />
                      <Text className={styles.offLineText}>设备已离线</Text>
                    </View>
                  )}
                </View>
              </View>
            ))}
        </View>
      </ScrollView>

      <CountdownActionSheet
        show={showCountDown}
        value={props[countDown] ?? 1}
        isSetModeOnly
        // mode="set"
        title={Strings.getLang('waterTime')}
        cancelText={Strings.getLang('cancel')}
        okText={Strings.getLang('confirm')}
        hourText={Strings.getLang('hour')}
        minuteText={Strings.getLang('min')}
        onClickOverlay={() => setShowCountDown(false)}
        onCancel={() => setShowCountDown(false)}
        onOk={parmas => {
          publishDps({
            [countDown]: parmas.value,
          });

          setShowCountDown(false);
        }}
      />

      <PageContainer
        show={show}
        customStyle={{
          backgroundColor: 'transparent',
        }}
        onClickOverlay={() => setShow(false)}
      >
        <View className={styles.groupDetialPage}>
          <Cell
            isLink
            title="设备组名称"
            value={select?.name || ''}
            onClick={() => {
              DialogInstance.input({
                title: '请输入名称',
                value: select?.name || '',
                beforeClose,
                cancelButtonText: Strings.getLang('cancel'),
                confirmButtonText: Strings.getLang('confirm'),
              });
            }}
          />
          <View className={styles.delBtn} onClick={handleDelete}>
            <Text>{Strings.getLang('deleteGroup')}</Text>
          </View>
        </View>

        <Dialog id="smart-dialog" />
      </PageContainer>
    </>
  );
};
